<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鲜时蔬 - 蔬菜列表</title>
    <!-- 核心依赖 -->
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 基础样式 -->
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: "Helvetica Neue", Helvetica, Arial, "PingFang SC", "Microsoft YaHei", sans-serif; background-color: #f8fafb; color: #333; }
        .container { width: 1140px; margin: 0 auto; padding: 0 15px; }
        @media (max-width: 1199px) { .container { width: 960px; } }
        @media (max-width: 991px) { .container { width: 720px; } }
        @media (max-width: 767px) { .container { width: 100%; } }

        /* 导航栏 */
        .header { background: #fff; box-shadow: 0 2px 10px rgba(0,0,0,0.08); position: fixed; top: 0; left: 0; right: 0; z-index: 1000; }
        .header-content { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; }
        .logo { display: flex; align-items: center; font-size: 22px; font-weight: bold; color: #27ae60; text-decoration: none; }
        .logo i { margin-right: 8px; }
        .nav { display: flex; }
        .nav a { margin: 0 15px; text-decoration: none; color: #555; font-size: 15px; padding: 5px 0; transition: all 0.3s; }
        .nav a:hover, .nav a.active { color: #27ae60; border-bottom: 2px solid #27ae60; }
        .user-actions { display: flex; align-items: center; }
        .user-actions button { margin-left: 15px; background: none; border: none; color: #666; cursor: pointer; font-size: 14px; display: flex; align-items: center; transition: all 0.3s; }
        .user-actions button:hover { color: #27ae60; }
        .user-actions button i { margin-right: 5px; }
        /* 用户信息下拉菜单 */
        .user-info { position: relative; display: flex; align-items: center; cursor: pointer; }
        .user-avatar { width: 32px; height: 32px; border-radius: 50%; background-color: #27ae60; color: white; display: flex; align-items: center; justify-content: center; margin-right: 8px; font-size: 14px; }
        .user-dropdown { position: absolute; top: 100%; right: 0; background: white; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px; padding: 5px 0; min-width: 120px; z-index: 10; margin-top: 5px; display: none; }
        .user-dropdown.show { display: block; }
        .user-dropdown-item { padding: 8px 15px; font-size: 14px; color: #606266; cursor: pointer; }
        .user-dropdown-item:hover { background-color: #f5f7fa; color: #27ae60; }

        /* 主内容区 */
        .main { padding-top: 90px; padding-bottom: 50px; }

        /* 筛选区 */
        .filter-section { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin-bottom: 25px; }
        .filter-row { display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 15px; align-items: center; }
        .filter-label { font-size: 14px; color: #555; width: 80px; text-align: right; font-weight: 500; }
        .filter-content { flex: 1; min-width: 200px; }
        .price-filter { display: flex; align-items: center; gap: 10px; }
        .price-filter input { width: 100px; }

        /* 蔬菜列表 */
        .vegetable-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 25px; margin-bottom: 30px; }
        .vegetable-card { background: #fff; border-radius: 10px; overflow: hidden; transition: all 0.3s ease; box-shadow: 0 5px 15px rgba(0,0,0,0.06); position: relative; }
        .vegetable-card:hover { transform: translateY(-8px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
        .vegetable-img-container { position: relative; overflow: hidden; }
        .vegetable-img { width: 100%; height: 180px; object-fit: cover; transition: transform 0.5s; }
        .vegetable-card:hover .vegetable-img { transform: scale(1.05); }
        .vegetable-info { padding: 16px; }
        .vegetable-name { font-size: 16px; margin-bottom: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; color: #333; }
        .vegetable-price { color: #e53935; font-weight: bold; font-size: 18px; margin-bottom: 12px; display: flex; align-items: center; }
        .vegetable-price del { color: #999; font-size: 13px; font-weight: normal; margin-left: 8px; }
        .shop-name { font-size: 13px; color: #666; margin-bottom: 12px; display: flex; align-items: center; }
        .shop-name i { margin-right: 5px; color: #888; }
        .card-actions { display: flex; justify-content: space-between; align-items: center; }
        .card-actions button { border-radius: 4px; }
        .vegetable-tags { margin: 10px 0; display: flex; flex-wrap: wrap; gap: 5px; }
        .vegetable-tag { display: inline-block; padding: 3px 8px; background: #f0f9eb; color: #67c23a; font-size: 11px; border-radius: 3px; }
        .vegetable-spec { font-size: 12px; color: #999; margin-bottom: 10px; }

        /* 分页 */
        .pagination { text-align: center; margin-top: 40px; }

        /* 页脚 */
        .footer { background: #2c3e50; color: #ecf0f1; padding: 40px 0; margin-top: 60px; }
        .footer-content { text-align: center; font-size: 14px; }

        /* 回到顶部 */
        .back-to-top { position: fixed; bottom: 30px; right: 30px; width: 45px; height: 45px; border-radius: 50%; background: #27ae60; color: #fff; border: none; cursor: pointer; display: none; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 999; transition: all 0.3s; }
        .back-to-top:hover { background: #2ecc71; transform: translateY(-3px); }
        .back-to-top.show { display: flex; }

        /* 详情弹框样式优化 */
        .detail-container { max-height: 70vh; overflow-y: auto; padding-right: 10px; }
        .detail-container::-webkit-scrollbar { width: 6px; }
        .detail-container::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
        .detail-container::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 10px; }
        .detail-container::-webkit-scrollbar-thumb:hover { background: #a8a8a8; }

        .detail-header { display: flex; gap: 25px; margin-bottom: 25px; padding-bottom: 25px; border-bottom: 1px solid #eee; }
        .detail-img { flex-shrink: 0; }
        .detail-img img { width: 220px; height: 220px; object-fit: cover; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); }

        .detail-basic { flex: 1; }
        .detail-basic div { margin-bottom: 12px; display: flex; }
        .detail-basic label { font-weight: 600; color: #555; width: 90px; flex-shrink: 0; }
        .detail-basic span { color: #333; }

        .detail-properties { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 25px; padding: 20px; background: #f9f9f9; border-radius: 8px; }
        .detail-properties div { display: flex; }
        .detail-properties label { font-weight: 600; color: #555; width: 120px; flex-shrink: 0; }
        .detail-properties span { color: #333; }

        .detail-spec { margin-top: 20px; }
        .detail-spec label { font-weight: bold; color: #555; display: block; margin-bottom: 12px; }
        .detail-spec pre { background: #f9f9f9; padding: 15px; border-radius: 6px; font-size: 13px; line-height: 1.5; border-left: 4px solid #27ae60; overflow-x: auto; }

        /* 空状态样式 */
        .empty-state { text-align: center; padding: 60px 20px; background: #fff; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .empty-state i { font-size: 50px; color: #ddd; margin-bottom: 15px; }
        .empty-state p { color: #888; font-size: 16px; }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .detail-header { flex-direction: column; }
            .detail-properties { grid-template-columns: 1fr; }
            .vegetable-list { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
        }
        .card-actions .el-button--success {
            margin-left: 8px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 导航栏 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html" class="active">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <!-- 根据登录状态显示不同内容 -->
                    <template v-if="isLoggedIn">
                        <div class="user-info" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                            <div class="user-avatar">
                                {{ userInfo.nickName ? userInfo.nickName.charAt(0) : userInfo.userName.charAt(0) }}
                            </div>
                            <span>{{ userInfo.nickName || userInfo.userName }}</span>
                            <div class="user-dropdown" :class="{ 'show': showDropdown }">
                                <div class="user-dropdown-item" @click="goToPersonalCenter">个人中心</div>
                                <div class="user-dropdown-item" @click="logout">退出登录</div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <button @click="goToLogin">
                            <i class="el-icon-user"></i> 登录
                        </button>
                    </template>
                    <button @click="goToCart">
                        <i class="el-icon-shopping-cart"></i> 购物车({{ cartCount }})
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="main">
        <div class="container">
            <!-- 面包屑 -->
            <el-breadcrumb separator="/" style="margin-bottom: 25px;">
                <el-breadcrumb-item><a href="index.html">首页</a></el-breadcrumb-item>
                <el-breadcrumb-item>蔬菜列表</el-breadcrumb-item>
            </el-breadcrumb>

            <!-- 筛选区 -->
            <div class="filter-section">
                <div class="filter-row">
                    <div class="filter-label">蔬菜分类：</div>
                    <div class="filter-content">
                        <el-select v-model="selectedCategoryId" placeholder="全部分类" @change="fetchProductList">
                            <el-option label="全部分类" value=""></el-option>
                            <el-option v-for="cat in categoryList" :key="cat.categoryId" :label="cat.categoryName" :value="cat.categoryId"></el-option>
                        </el-select>
                    </div>
                </div>
                <div class="filter-row">
                    <div class="filter-label">价格范围：</div>
                    <div class="filter-content price-filter">
                        <el-input v-model="priceMin" placeholder="最低价格" type="number" min="0" step="0.01"></el-input>
                        <span>-</span>
                        <el-input v-model="priceMax" placeholder="最高价格" type="number" min="0" step="0.01"></el-input>
                        <el-button type="primary" size="mini" @click="fetchProductList">筛选</el-button>
                    </div>
                </div>
                <div class="filter-row">
                    <div class="filter-label">排序方式：</div>
                    <div class="filter-content">
                        <el-radio-group v-model="sortType" @change="fetchProductList">
                            <el-radio label="price_asc">价格从低到高</el-radio>
                            <el-radio label="price_desc">价格从高到低</el-radio>
                            <el-radio label="createTime_desc">最新上架</el-radio>
                        </el-radio-group>
                    </div>
                </div>
            </div>

            <!-- 商品列表：展示商品（名称、价格、图片等） -->
            <div class="vegetable-list" v-if="productList.length > 0">
                <div class="vegetable-card" v-for="(product, index) in productList" :key="product.productId">
                    <div class="vegetable-img-container">
                        <!-- 商品图片：优先使用后端返回的图片URL，无图时用默认图 -->
                        <img :src="product.imageUrl ? product.imageUrl : 'https://picsum.photos/id/292/250/180'"
                             :alt="product.productName"
                             class="vegetable-img">
                    </div>
                    <div class="vegetable-info">
                        <!-- 商品名称 -->
                        <div class="vegetable-name">{{ product.productName }}</div>
                        <!-- 商品价格 -->
                        <div class="vegetable-price">
                            ¥{{ product.price || '暂无价格' }}
                            <del v-if="product.originalPrice">¥{{ product.originalPrice }}</del>
                        </div>
                        <!-- 新增：调用接口查询并展示店铺名称 -->
                        <div class="shop-name">
                            <i class="el-icon-office-building"></i>
                            店铺：{{ getShopName(product.productId) }}
                        </div>
                        <!-- 操作按钮 -->
                        <div class="card-actions">
                            <el-button type="text" @click="goToDetail(product.productId)">查看详情</el-button>
                            <el-button type="primary" size="mini" @click="addToCart(product)">加入购物车</el-button>
                            <el-button type="success" size="mini" @click="buyNow(product)">立即购买</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 无商品时的空状态 -->
            <div v-else class="empty-state">
                <i class="el-icon-search"></i>
                <p>未找到符合条件的商品</p>
            </div>

            <!-- 分页：关联后端返回的总条数 -->
            <div class="pagination" v-if="total > 0">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[4, 8, 12, 16]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                ></el-pagination>
            </div>
        </div>
    </main>
    <!-- 商品详情弹框 -->
    <el-dialog
            title="商品详情"
            :visible.sync="detailDialogVisible"
            width="70%"
            :before-close="handleDialogClose"
            custom-class="custom-dialog"
    >
        <div class="detail-container">
            <!-- 商品基础信息（左侧图片 + 右侧基础属性） -->
            <div class="detail-header">
                <!-- 商品图片 -->
                <div class="detail-img">
                    <img
                            :src="currentProduct.imageUrl ? currentProduct.imageUrl : 'https://picsum.photos/id/292/220/220'"
                            :alt="currentProduct.productName"
                    >
                </div>
                <!-- 基础属性（名称、价格、店铺） -->
                <div class="detail-basic">
                    <div>
                        <label>商品名称：</label>
                        <span>{{ currentProduct.productName || '暂无数据' }}</span>
                    </div>
                    <div>
                        <label>商品价格：</label>
                        <span style="color: #e53935; font-weight: bold; font-size: 18px;">¥{{ currentProduct.price || '暂无数据' }}</span>
                    </div>
                    <div>
                        <label>所属店铺：</label>
                        <span>{{ currentProduct.shopName || '暂无数据' }}</span>
                    </div>
                    <div>
                        <label>上架时间：</label>
                        <span>{{ formatDate(currentProduct.createTime) || '暂无数据' }}</span>
                    </div>
                    <div>
                        <label>商品描述：</label>
                        <span>{{ currentProduct.description || '暂无描述信息' }}</span>
                    </div>
                </div>
            </div>

            <!-- 商品关联属性（分类、单位、品牌等） -->
            <div class="detail-properties">
                <!--<div>
                    <label>分类ID：</label>
                    <span>{{ currentProduct.categoryId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>分类名称：</label>
                    <span>{{ currentProduct.category?.categoryName || '暂无数据' }}</span>
                </div>
                <!--<div>
                    <label>单位ID：</label>
                    <span>{{ currentProduct.unitId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>单位名称：</label>
                    <span>{{ currentProduct.unit?.unitName || '暂无数据' }}</span>
                </div>
               <!-- <div>
                    <label>品牌ID：</label>
                    <span>{{ currentProduct.brandId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>品牌名称：</label>
                    <span>{{ currentProduct.brand?.brandName || '暂无数据' }}</span>
                </div>
                <!--<div>
                    <label>品种ID：</label>
                    <span>{{ currentProduct.varietyId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>品种名称：</label>
                    <span>{{ currentProduct.variety?.varietyName || '暂无数据' }}</span>
                </div>
                <!--<div>
                    <label>产地ID：</label>
                    <span>{{ currentProduct.originId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>产地名称：</label>
                    <span>{{ currentProduct.origin?.originName || '暂无数据' }}</span>
                </div>
                <!--<div>
                    <label>等级ID：</label>
                    <span>{{ currentProduct.gradeId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>等级名称：</label>
                    <span>{{ currentProduct.grade?.gradeName || '暂无数据' }}</span>
                </div>
                <!--<div>
                    <label>冷藏方式ID：</label>
                    <span>{{ currentProduct.coldId || '暂无数据' }}</span>
                </div>-->
                <div>
                    <label>冷藏方式名称：</label>
                    <span>{{ currentProduct.cold?.coldName || '暂无数据' }}</span>
                </div>
            </div>

            <!-- 规格信息（JSON 格式化展示） -->
            <div class="detail-spec">
                <label>规格信息：</label>
                <pre v-if="formattedSpec">{{ formattedSpec }}</pre>
                <span v-else style="color: #999;">暂无规格数据</span>
            </div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="detailDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addToCart(currentProduct)">加入购物车</el-button>
        </span>
    </el-dialog>
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>

    <!-- 回到顶部 -->
    <button class="back-to-top" :class="{ 'show': scrollY > 500 }" @click="scrollToTop">
        <i class="el-icon-arrow-up"></i>
    </button>
</div>

<!-- Vue 逻辑 -->
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                showDropdown: false, // 控制下拉菜单显示
                isLoggedIn: false,   // 登录状态
                userInfo: {},        // 用户信息
                scrollY: 0,
                cartCount: 0, // 购物车数量

                // 筛选条件
                selectedCategoryId: '', // 选中的分类ID（关联category表）
                priceMin: '', // 最低售价
                priceMax: '', // 最高售价
                sortType: 'createTime_desc', // 排序方式：createTime_desc（最新）、price_asc（低价）、price_desc（高价）

                // 分页参数
                currentPage: 1,
                pageSize: 8,
                total: 0, // 总条数

                // 分类列表（从/category/queryCategoryTree接口获取）
                categoryList: [],
                // 商品列表（从/product/selectProductList接口获取）
                productList: [],
                shopNameMap: {}, // 新增：存储 productId -> 店铺名称的映射，避免重复请求
                detailDialogVisible: false, // 详情弹框显示状态
                currentProduct: {}, // 当前查看详情的商品完整信息
                formattedSpec: '' // 格式化后的规格信息（JSON 转字符串）
            }
        },
        mounted() {
            window.addEventListener('scroll', () => this.scrollY = window.scrollY);
            // 【接口调用】初始化数据
            this.fetchCategoryList();
            this.fetchProductList();
            this.fetchCartCount();
            this.checkLoginStatus();
        },
        beforeDestroy() {
            window.removeEventListener('scroll', () => this.scrollY = window.scrollY);
        },
        methods: {
            /**
             * 检查登录状态
             */
            checkLoginStatus() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200 && response.data.data) {
                            this.isLoggedIn = true;
                            this.userInfo = response.data.data;
                        } else {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                        }
                    })
                    .catch(error => {
                        console.error('检查登录状态失败:', error);
                        this.isLoggedIn = false;
                    });
            },
            /**
             * 登出
             */
            logout() {
                axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                    .then(response => {
                        if (response.data.code === 200) {
                            this.isLoggedIn = false;
                            this.userInfo = {};
                            this.showDropdown = false;
                            this.$message.success('退出登录成功');
                            setTimeout(() => this.goToLogin(), 1000);
                        } else {
                            this.$message.error('退出登录失败');
                        }
                    })
                    .catch(error => {
                        console.error('退出登录失败:', error);
                        this.$message.error('退出登录失败');
                    });
            },
            /**
             * 跳转到个人中心
             */
            goToPersonalCenter() {
                this.$message.info('即将跳转到个人中心');
                window.location.href = '/vegetablemarketexpress/html/front/personalCenter.html';
            },
            // 回到顶部
            scrollToTop() {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            },
            // 跳转页面
            goToLogin() { window.location.href = 'login.html'; },
            goToCart() { window.location.href = 'shoppingCart.html'; },



            // 获取商品分类列表（对接后端/category/queryByPage）
            fetchCategoryList() {
                axios.post('/vegetablemarketexpress/category/queryByPage',{
                    "pageNo": 1,
                    "pageSize": 100,
                })
                    .then(res => {
                        if (res.data.code === 200 && res.data.data) {
                            this.categoryList = res.data.data.list;
                        } else {
                            this.$message.warning('分类列表加载失败');
                        }
                    })
                    .catch(err => {
                        console.error('分类列表请求异常：', err);
                        this.$message.error('网络错误，请重试');
                    });
            },
            /**
             * 2. 获取商品列表（对接后端/product/selectProductList接口，带筛选和分页）
             */
            fetchProductList() {
                // 构造后端需要的Page参数（与后端Page<Product>实体对应）
                const pageParam = {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                    data: {
                        // 筛选条件：分类ID、售价范围（与Product实体字段对应）
                        categoryId: this.selectedCategoryId || undefined,
                        minPrice: this.priceMin ? Number(this.priceMin) : undefined, // 转数字避免字符串
                        maxPrice: this.priceMax ? Number(this.priceMax) : undefined,
                        sortType: this.sortType // 确保排序参数被传递
                    }
                };

                axios.post('/vegetablemarketexpress/product/selectProductList', pageParam)
                    .then(res => {
                        if (res.data.code === 200 && res.data.data) {
                            this.productList = res.data.data.list || [];
                            this.total = res.data.data.total || 0;
                        } else {
                            this.productList = [];
                            this.total = 0;
                            this.$message.warning('商品列表加载失败');
                        }
                    })
                    .catch(err => {
                        console.error('商品列表请求异常：', err);
                        this.productList = [];
                        this.total = 0;
                        this.$message.error('网络错误，请重试');
                    });
            },
            /**
             * 获取店铺名称
             * @param productId
             */
            getShopName(productId) {
                //  先从映射中取，避免重复请求
                if (this.shopNameMap[productId]) {
                    return this.shopNameMap[productId];
                }
                axios.post(`/vegetablemarketexpress/shopProduct/getShopNameByProductId?productId=${productId}`, {})
                    .then(res => {
                        if (res.data.code === 200) {
                            // 3. 存储到映射中，下次直接使用
                            this.shopNameMap[productId] = res.data.data;
                        } else {
                            this.shopNameMap[productId] = "获取失败";
                        }
                    })
                    .catch(err => {
                        console.error("查询店铺名称失败", err);
                        return "查询失败";
                    });
            },
            /**
             * 修改goToDetail方法，从现有列表数据中获取商品详情
             * @param productId 商品ID
             */
            goToDetail(productId) {
                // 从已加载的商品列表中查找当前商品
                const product = this.productList.find(item => item.productId === productId);
                if (product) {
                    this.currentProduct = product;
                    // 格式化规格信息（注意字段名是specJson而不是specInfo）
                    this.formatSpecData(this.currentProduct.specJson);
                    // 获取店铺名称
                    this.getShopNameForDetail(productId);
                    this.detailDialogVisible = true;
                } else {
                    this.$message.warning('商品信息获取失败');
                }
            },
            /**
             * 为详情弹框查询店铺名称
             */
            getShopNameForDetail(productId) {
                if (this.shopNameMap[productId]) {
                    this.currentProduct.shopName = this.shopNameMap[productId];
                    return;
                }
                axios.post(`/vegetablemarketexpress/shopProduct/getShopNameByProductId?productId=${productId}`, {})
                    .then(res => {
                        if (res.data.code === 200) {
                            this.shopNameMap[productId] = res.data.data;
                            this.currentProduct.shopName = res.data.data;
                        } else {
                            this.shopNameMap[productId] = "获取失败";
                            this.currentProduct.shopName = "获取失败";
                        }
                    })
                    .catch(err => {
                        console.error("查询店铺名称失败", err);
                        this.currentProduct.shopName = "查询失败";
                    });
            },
            /**
             * 格式化规格信息（JSON 字符串转带缩进的格式）
             * @param specJson 后端返回的规格 JSON 字符串
             */
            formatSpecData(specJson) {
                if (!specJson) {
                    this.formattedSpec = '';
                    return;
                }
                try {
                    // 解析 JSON 并格式化为带 2 个空格缩进的字符串
                    const specObj = typeof specJson === 'string' ? JSON.parse(specJson) : specJson;
                    this.formattedSpec = JSON.stringify(specObj, null, 2);
                } catch (e) {
                    console.error('规格信息解析失败：', e);
                    this.formattedSpec = '规格格式错误，无法解析';
                }
            },

            /**
             * 日期格式化
             * @param dateStr 后端返回的日期字符串
             */
            formatDate(dateStr) {
                if (!dateStr) return '';
                const date = new Date(dateStr);
                return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            },
            /**
             * 关闭弹框时重置数据
             */
            handleDialogClose() {
                this.detailDialogVisible = false;
                this.currentProduct = {};
                this.formattedSpec = '';
            },

            /**
             * 4. 分页事件：每页条数改变
             */
            handleSizeChange(pageSize) {
                this.pageSize = pageSize;
                this.currentPage = 1; // 重置为第一页
                this.fetchProductList();
            },

            /**
             * 5. 分页事件：当前页码改变
             */
            handleCurrentChange(currentPage) {
                this.currentPage = currentPage;
                this.fetchProductList();
            },

            /**
             *加入购物车
             */
            addToCart(product) {
                // 校验登录状态（未登录则提示）
                if (!this.isLoggedIn) {
                    this.$message.warning('请先登录再加入购物车');
                    this.goToLogin();
                    return;
                }
                // 构造请求参数
                const cartParam = {
                    productId: product.productId,
                    productCount: 1, // 默认添加1件
                    productName: product.productName,
                    productPrice: product.price,
                    // 若需传递单位、店铺等信息，可补充：
                    // unit: product.unit,
                    // shopId: product.shopId,
                    shopName: product.shopName,
                    imageUrl: product.imageUrl // 携带商品图片
                };
                // 调用后端“加入购物车”接口（携带Cookie保持登录态）
                axios.post('/vegetablemarketexpress/shoppingCart/add', cartParam, {
                    withCredentials: true
                })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.$message.success(`"${product.productName}" 成功添加到购物车`);
                            this.fetchCartCount(); // 更新购物车数量显示
                        } else {
                            this.$message.warning(res.data.message || `"${product.productName}" 加入购物车失败`);
                        }
                    })
                    .catch(err => {
                        console.error('加入购物车异常：', err);
                        this.$message.error('网络错误，请重试');
                    });
            },
            /**
             *获取购物车数量
             */
            fetchCartCount() {
                axios.get('/vegetablemarketexpress/shoppingCart/count', {
                    withCredentials: true
                })
                    .then(res => {
                        console.log('购物车数据：', res.data.data); // 查看返回的购物车数据
                        if (res.data.code === 200) {
                            this.cartCount = res.data.data || 0;
                        }
                    })
                    .catch(err => {
                        console.error('购物车数量请求异常：', err);
                        this.cartCount = 0; // 异常时置为0
                    });
            },
            /**
             * 立即购买
             * @param product
             */
            buyNow(product) {
                // 校验登录状态
                if (!this.isLoggedIn) {
                    this.$message.warning('请先登录再购买');
                    this.goToLogin();
                    return;
                }

                // 构造与购物车一致的订单数据结构
                const orderItem = {
                    productId: product.productId,
                    productName: product.productName,
                    productPrice: product.price,
                    productCount: 1,
                    imageUrl: product.imageUrl,
                    shopName: this.shopNameMap[product.productId] || '未知店铺'
                };

                // 跳转到 createOrder.html 并带上商品数据
                const cartData = encodeURIComponent(JSON.stringify([orderItem]));
                window.location.href = `createOrder.html?cartData=${cartData}`;
            }
        }
    });
</script>
</body>
</html>